<?php

namespace app\api\controller;

use app\common\controller\Api;
use fast\Random;
use think\Validate;
use think\Page;
use think\Db;
class Message extends Api
{ 
    // protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';
    protected $user_id = 0;

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
    }

    /**
     * 消息列表
     * 
    */
    public function index()
    {
        $user_id = $this->user_id;
        $user = db('user')
                ->where(['id'=>$user_id])
                ->find();

        $type_arr = [];
        $type_arr['-1']['type'] = -1;
        $type_arr['-1']['num'] = db('article_history')->where(['user_id'=>$user_id,'type'=>'1'])->count();
        $type_arr['-2']['type'] = -2;
        $type_arr['-2']['num'] = db('article_history')->where(['user_id'=>$user_id,'type'=>'2'])->count();
        $type_arr['-3']['type'] = -3;
        $type_arr['-3']['num'] = db('article_history')->where(['user_id'=>$user_id,'type'=>'3'])->count();
        $type_arr['-4']['type'] = -4;
        $type_arr['-4']['num'] = db('article_history')->where(['user_id'=>$user_id,'type'=>'4'])->count();
        $type_arr['-5']['type'] = -5;
        $type_arr['-5']['num'] = db('article_history')->where(['user_id'=>$user_id,'type'=>'5'])->count();
        $type_arr = array_sort_two($type_arr,'num','desc');
        $relation_notin_ids = [-1,-2,-3,-4,-5];
        $relation_top_id = $type_arr[0]['type'];
        $relation_notin_ids = array_merge(array_diff($relation_notin_ids, array($relation_top_id)));;


        $reg_time = $user['createtime'];

        $sql = db('user_message')
        ->alias('m')
        ->field('m1.message_id,m1.title,m1.message,m1.createtime,m1.relation_id,m1.source,IF(sm.type IS NULL,0,1) type')
        ->join('message m1','m1.message_id = m.message_id','left')
        ->join('sys_message_log sm','sm.message_id = m1.message_id AND sm.user_id = '.$user_id,'LEFT');
        $sql = $sql->where(function ($query) use($user_id,$reg_time,$relation_notin_ids) {
            $query->where(['m.user_id'=>$user_id,'m1.createtime'=>['gt',$reg_time],'m1.relation_id'=>['not in',$relation_notin_ids]])->where(function ($q) use($user_id) {
                $q->whereOr(['sm.id'=>null,'sm.type'=>['neq',2]]);
            });
        })->whereOr(function ($query) use($user_id,$reg_time,$relation_notin_ids) {
            $query->where(['m.user_id'=>0,'m1.createtime'=>['gt',$reg_time],'m1.relation_id'=>['not in',$relation_notin_ids]])->where(function ($c) use($user_id) {
                $c->whereOr(['sm.id'=>null,'sm.type'=>['neq',2]]);
            });
        });

        $sql = $sql
                ->order('m1.message_id desc')
                ->limit('10000000')
                ->buildSql();




        $list_buf = Db::table($sql.' a')
            ->order('type asc,message_id desc')
            ->group('relation_id')
            ->select();
            
        $list = [];
        foreach ($list_buf as $key => $value) {
            if ( !isset($list[$value['source']]) ) {
                $list[$value['source']] = $value;
            }
            
        }
        $buf = [];
        foreach ($list as $key => $value) {
            $buf[] = $value;
        }


        $this->success('請求成功',$buf);
    }

    /*
    *查看信息
     */
    public function message($value='')
    {
        $user_id = $this->user_id;
        $message_id = input('post.message_id',0);

        $data = db('user_message')
        ->alias('m')
        ->field('m1.message_id,m1.title,m1.message,m1.createtime,m1.relation_id,m1.source,m1.type,m.user_id')
        ->join('message m1','m1.message_id = m.message_id')
        ->join('sys_message_log sm','sm.message_id = m1.message_id AND sm.user_id = '.$user_id,'LEFT')
        ->where(['m1.message_id'=>$message_id])
        ->find();

        if ( !$data ) {
            $this->success('請求成功',[]);
        }

        if ( $data['type'] == 1 && $data['user_id'] != $user_id ) {
            $this->success('請求成功',[]);
        }


        $relation_id = $data['relation_id'];
        $source = $data['source'];

        $list = db('user_message')
        ->alias('m')
        ->field('m1.message_id,m1.title,m1.message,m1.relation_id,m1.source')
        ->join('message m1','m1.message_id = m.message_id')
        ->join('sys_message_log sm','sm.message_id = m1.message_id AND sm.user_id = '.$user_id,'LEFT');
            $list = $list->where(function ($query) use($user_id,$relation_id,$source) {
                $query->where(['m.user_id'=>$user_id,'m1.relation_id'=>$relation_id,'m1.source'=>$source])->where(function ($q) use($user_id) {
                    $q->whereOr(['sm.id'=>null,'sm.type'=>['neq',2]]);
                });
            })->whereOr(function ($query) use($user_id,$relation_id,$source) {
                $query->where(['m.user_id'=>0,'m1.relation_id'=>$relation_id,'m1.source'=>$source])->where(function ($c) use($user_id) {
                    $c->whereOr(['sm.id'=>null,'sm.type'=>['neq',2]]);
                });
            });

        $list = $list
                ->group('m.message_id')
                ->select();
        $time = time();
        foreach ($list as $key => $value) {
            $count = db('sys_message_log')
                    ->where(['message_id'=>$value['message_id'],'user_id'=>$user_id])
                    ->count();
            if ( !$count ) {
                db('sys_message_log')
                ->insertGetId(['message_id'=>$value['message_id'],'user_id'=>$user_id,'createtime'=>$time,'type'=>1]);
            }
        }

        unset( $data['type'] );
        unset( $data['user_id'] );
        $this->success('请求成功',$data);
    }

    /*
    *已读
    */
    public function seeMessage($value='')
    {

        $user_id = $this->user_id;
        $message_id = input('post.message_id',0);

        $data = db('user_message')
        ->alias('m')
        ->field('m1.message_id,m1.title,m1.message,m1.createtime,m1.relation_id,m1.source,m1.type,m.user_id')
        ->join('message m1','m1.message_id = m.message_id')
        ->join('sys_message_log sm','sm.message_id = m1.message_id AND sm.user_id = '.$user_id,'LEFT')
        ->where(['m1.message_id'=>$message_id])
        ->find();

        if ( !$data ) {
            $this->success('操作成功');
        }

        if ( $data['type'] == 1 && $data['user_id'] != $user_id ) {
            $this->success('操作成功');
        }

        $relation_id = $data['relation_id'];
        $source = $data['source'];

        $list = db('user_message')
        ->alias('m')
        ->field('m1.message_id,m1.title,m1.message,m1.relation_id,m1.source')
        ->join('message m1','m1.message_id = m.message_id')
        ->join('sys_message_log sm','sm.message_id = m1.message_id AND sm.user_id = '.$user_id,'LEFT');
            $list = $list->where(function ($query) use($user_id,$relation_id,$source) {
                $query->where(['m.user_id'=>$user_id,'m1.relation_id'=>$relation_id,'m1.source'=>$source])->where(function ($q) use($user_id) {
                    $q->whereOr(['sm.id'=>null,'sm.type'=>['neq',2]]);
                });
            })->whereOr(function ($query) use($user_id,$relation_id,$source) {
                $query->where(['m.user_id'=>0,'m1.relation_id'=>$relation_id,'m1.source'=>$source])->where(function ($c) use($user_id) {
                    $c->whereOr(['sm.id'=>null,'sm.type'=>['neq',2]]);
                });
            });

        $list = $list
                ->group('m.message_id')
                ->select();
        $time = time();
        foreach ($list as $key => $value) {
            $count = db('sys_message_log')
                    ->where(['message_id'=>$value['message_id'],'user_id'=>$user_id])
                    ->count();
            if ( !$count ) {
                db('sys_message_log')
                ->insertGetId(['message_id'=>$value['message_id'],'user_id'=>$user_id,'createtime'=>$time,'type'=>1]);
            }
        }

        $this->success('操作成功');
    }

    /**
     * 獲取未讀消息數量，目前就只有系統消息
     * 
    */
    public function getNoReadNum()
    {
        $user_id = $this->user_id;
        $user = db('user')
                ->where(['id'=>$user_id])
                ->find();

        $type_arr = [];
        $type_arr['-1']['type'] = -1;
        $type_arr['-1']['num'] = db('article_history')->where(['user_id'=>$user_id,'type'=>'1'])->count();
        $type_arr['-2']['type'] = -2;
        $type_arr['-2']['num'] = db('article_history')->where(['user_id'=>$user_id,'type'=>'2'])->count();
        $type_arr['-3']['type'] = -3;
        $type_arr['-3']['num'] = db('article_history')->where(['user_id'=>$user_id,'type'=>'3'])->count();
        $type_arr['-4']['type'] = -4;
        $type_arr['-4']['num'] = db('article_history')->where(['user_id'=>$user_id,'type'=>'4'])->count();
        $type_arr['-5']['type'] = -5;
        $type_arr['-5']['num'] = db('article_history')->where(['user_id'=>$user_id,'type'=>'5'])->count();
        $type_arr = array_sort_two($type_arr,'num','desc');
        $relation_notin_ids = [-1,-2,-3,-4,-5];
        $relation_top_id = $type_arr[0]['type'];
        $relation_notin_ids = array_merge(array_diff($relation_notin_ids, array($relation_top_id)));;


        $reg_time = $user['createtime'];

        $sql = db('user_message')
        ->alias('m')
        ->field('m1.message_id,m1.title,m1.message,m1.createtime,m1.relation_id,m1.source,IF(sm.type IS NULL,0,1) type')
        ->join('message m1','m1.message_id = m.message_id','left')
        ->join('sys_message_log sm','sm.message_id = m1.message_id AND sm.user_id = '.$user_id,'LEFT');
        $sql = $sql->where(function ($query) use($user_id,$reg_time,$relation_notin_ids) {
            $query->where(['m.user_id'=>$user_id,'m1.createtime'=>['gt',$reg_time],'m1.relation_id'=>['not in',$relation_notin_ids],'sm.id'=>null]);
        })->whereOr(function ($query) use($user_id,$reg_time,$relation_notin_ids) {
            $query->where(['m.user_id'=>0,'m1.createtime'=>['gt',$reg_time],'m1.relation_id'=>['not in',$relation_notin_ids],'sm.id'=>null]);
        });

        $sql = $sql
                ->order('m1.message_id desc')
                ->buildSql();




        $list_buf = Db::table($sql.' a')
            ->order('type asc,message_id desc')
            ->group('relation_id')
            ->select();

        $list = [];
        foreach ($list_buf as $key => $value) {
            if ( !isset($list[$value['source']]) ) {
                $list[$value['source']] = $value;
            }
            
        }
        $buf = [];
        foreach ($list as $key => $value) {
            $buf[] = $value;
        }

        $system_num = count($buf);
        $this->success('請求成功',['system_num'=>$system_num]);
    }

}